package marksys.free.com.marksys.nettool.retrofit;


import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import java.util.concurrent.TimeUnit;


import marksys.free.com.marksys.nettool.Constant;
import marksys.free.com.marksys.nettool.MyApi;
import marksys.free.com.marksys.utils.SharedPreferencesUtils;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import timber.log.Timber;


/**
 * Created by zlinsun on 2018/7/31.
 * hah
 */
public class RetrofitUtils {
    public MyApi.ApiService apiService;
    private static final int DEFAULT_TIMEOUT = 5;

    private static class SingletonHolder {
        private static RetrofitUtils INSTANCE = new RetrofitUtils();
    }

    public static RetrofitUtils getInstance() {
        return SingletonHolder.INSTANCE;
    }


    private static final String TAG = "RetrofitUtils";

    public RetrofitUtils() {
        Log.i(TAG, "RetrofitUtils: ");
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //.addInterceptor(new BaseInterceptor())
                .addNetworkInterceptor((Interceptor.Chain chain) -> {
                    Request original = chain.request();
                    Request.Builder newBuilder = original.newBuilder();
                    String token = SharedPreferencesUtils.getString(Constant.UserToken, "");
                    if (!TextUtils.isEmpty(token)) {
                        newBuilder.addHeader("Token", token);
                    }
                    Timber.v("OKHttp Request URL= [%s]", original.url());
                    if ("POST".equals(original.method())) {
                        RequestBody bodyUnSign = original.body();
                        assert bodyUnSign != null;
                        newBuilder.post(bodyUnSign);
                    } else {
                        newBuilder.get();
                    }
                    Request request = newBuilder.build();
                    return chain.proceed(request);
                })
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(new LiveDataCallAdapterFactory())
                .client(okHttpClient)
                .build();
        apiService = retrofit.create(MyApi.ApiService.class);
    }

}
